import type { S2DataConfig, S2Options } from '@antv/s2';
import { PivotSheet } from '@antv/s2';
import { Card, Radio } from 'antd';
import { useEffect, useState } from 'react';
import numeral from 'numeral';
const PALETTE_COLORS = [
  {
    limit: -50,
    background: 'rgb(62,144,109)',
    color: 'black',
  },
  {
    limit: -35,
    background: 'rgb(74,181,120)',
    color: 'black',
  },
  {
    limit: -20,
    background: 'rgb(112,196,121)',
    color: 'black',
  },
  {
    limit: -5,
    background: 'rgb(150,212,164)',
    color: 'black',
  },
  {
    limit: 10,
    background: 'rgb(190,226,188)',
    color: 'black',
  },
  {
    limit: 25,
    background: 'rgb(238,229,229)',
    color: 'black',
  },
  {
    limit: 40,
    background: 'rgb(243,187,161)',
    color: 'white',
  },
  {
    limit: 55,
    background: 'rgb(238,154,119)',
    color: 'white',
  },
  {
    limit: 70,
    background: 'rgb(235,123,85)',
    color: 'white',
  },
  {
    limit: 85,
    background: 'rgb(230,91,55)',
    color: 'white',
  },
  {
    limit: 100,
    background: 'rgb(214,61,33)',
    color: 'white',
  },
];
const getTargetColor = (value: number) =>
  PALETTE_COLORS.find((color) => color.limit >= value) ?? PALETTE_COLORS[PALETTE_COLORS.length - 1];

// 属性类型
type PropField = {
  title: string;
  data: API.DeptJfData[];
};
const BmywTable: React.FC<PropField> = (props) => {
  const [valType, setValType] = useState(1);
  useEffect(() => {
    const dqvCol = valType === 1 ? 'ztZyCurrVal' : valType === 2 ? 'jxedCurrVal' : 'fyedCurrVal';
    const qnvCol = valType === 1 ? 'ztZyQntqVal' : valType === 2 ? 'jxedQntqVal' : 'fyedQntqVal';
    const rowDatas = props.data.map((item) => ({
      ...item,
      zl: item[dqvCol] - item[qnvCol],
      zf: (item[dqvCol] - item[qnvCol]) / item[qnvCol],
    }));
    const container = document.getElementById('container_bmyw');
    const s2DataConfig: S2DataConfig = {
      fields: {
        rows: ['dptp', 'dpnm'],
        values: [dqvCol, qnvCol, 'zl', 'zf'],
        valueInCols: true,
      },
      meta: [
        {
          field: 'dptp',
          name: '类别',
        },
        {
          field: 'dpnm',
          name: '部门',
        },
        {
          field: dqvCol,
          name: '今年',
          formatter: (v) => numeral(v).format('0,0'),
        },
        {
          field: qnvCol,
          name: '去年同期',
          formatter: (v) => numeral(v).format('0,0'),
        },
        {
          field: 'zl',
          name: '增量',
          formatter: (v) => numeral(v).format('0,0'),
        },
        {
          field: 'zf',
          name: '增幅',
          formatter: (v) => numeral(v).format('0.00%'),
        },
      ],
      data: rowDatas,
    };
    const s2Options: S2Options = {
      width: 708,
      height: 368,
      hierarchyType: 'tree',
      tooltip: {
        enable: true,
      },
      conditions: {
        text: [
          {
            field: 'zf',
            mapping(value: number | string) {
              const { color } = getTargetColor((value as number) * 100);
              return {
                fill: color,
              };
            },
          },
        ],
        background: [
          {
            field: 'zf',
            mapping(value: number | string) {
              const { background } = getTargetColor((value as number) * 100);
              return {
                fill: background,
              };
            },
          },
        ],
      },
      totals: {
        row: {
          showSubTotals: true,
          reverseSubTotalsLayout: true,
          subTotalsDimensions: ['txName'],
          calcSubTotals: {
            calcFunc: (query, data) => {
              const cname: string = query.$$extra$$;
              let sum = 0;
              if (cname === 'zf' || cname === 'zl') {
                let sum1 = 0;
                let sum2 = 0;
                data.forEach((item) => {
                  sum1 += item.raw[dqvCol] ? item.raw[dqvCol] : 0;
                });
                data.forEach((item) => {
                  sum2 += item.raw[qnvCol] ? item.raw[qnvCol] : 0;
                });
                if (cname === 'zf') {
                  sum = (sum1 - sum2) / sum2;
                } else {
                  sum = sum1 - sum2;
                }
              } else {
                data.forEach((item) => {
                  sum += item.raw[cname];
                });
              }
              return sum;
            },
          },
        },
      },
      interaction: {
        selectedCellsSpotlight: true,
        hoverHighlight: true,
        copy: { enable: true },
      },
    };
    const s2 = new PivotSheet(container!, s2DataConfig, s2Options);
    s2.setThemeCfg({ name: 'gray' });
    s2.render();
  }, [props.data, valType]);
  return (
    <Card
      size="small"
      title={props.title}
      extra={
        <Radio.Group
          value={valType}
          size="small"
          onChange={(e) => setValType(Number(e.target.value))}
        >
          <Radio.Button key={1} value={1}>
            整体资源
          </Radio.Button>
          <Radio.Button key={2} value={2}>
            绩效额度
          </Radio.Button>
          <Radio.Button key={3} value={3}>
            费用额度
          </Radio.Button>
        </Radio.Group>
      }
      bodyStyle={{ height: '368px', padding: '0px' }}
      style={{ paddingRight: '16px' }}
    >
      <div id="container_bmyw" />
    </Card>
  );
};
export default BmywTable;
